package com.yanqu.road.server.manager.activity;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.enums.eActivityType;
import com.yanqu.road.entity.enums.eCrossRankActivityType;
import com.yanqu.road.entity.enums.eMessageType;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.helper.CrossChannelHelper;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.worldmessage.WorldMessageProto;
import com.yanqu.road.server.CrossBattleServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.cross3server.manager.Cross3EnterNameMgr;
import com.yanqu.road.server.logic.MessageHelper;
import com.yanqu.road.server.manager.activity.jiuzhou.CrossJiuZhouMgr;
import com.yanqu.road.server.manager.activity.jiuzhou.activity.CrossJiuZhouActivity;
import com.yanqu.road.server.manager.activity.peakseacraft.PeakSeacraftActivity;
import com.yanqu.road.server.manager.activity.peakseacraft.PeakSeacraftMgr;
import com.yanqu.road.server.manager.activity.rankunionwar.CrossRankUnionWarMgr;
import com.yanqu.road.server.manager.activity.rankunionwar.activity.CrossRankUnionWarActivity;
import com.yanqu.road.server.manager.activity.suitang.CrossSuiTangMgr;
import com.yanqu.road.server.manager.activity.suitang.activity.CrossSuiTangActivity;
import com.yanqu.road.server.manager.activity.tonbing.CrossTonBingMgr;
import com.yanqu.road.server.manager.activity.tonbing.activity.CrossTonBingActivity;
import com.yanqu.road.server.manager.peakstronghold.CrossPeakStrongholdMgr;
import com.yanqu.road.server.manager.peakstronghold.PeakStrongholdActivityModel;
import com.yanqu.road.server.manager.union.activitygroup.Cross2UnionActivityGroupMgr;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.protocol.AgentProtocol;
import com.yanqu.road.server.protocol.ChannelProtocol;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.ConfigHelper;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.string.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class ActivityChatMgr extends TempMgr {

    public static final int MAX_MESSAGE_COUNT = 50;

    private static Map<Integer,Map<Integer, WorldMessageProto.WorldMessageListMsg.Builder>> chatMsgMap;

    private static Map<String, WorldMessageProto.WorldMessageListMsg.Builder> chatExtensionMsgMap;

    @Override
    public boolean reloadData() {
        chatMsgMap = new ConcurrentHashMap<>();
        chatExtensionMsgMap = new ConcurrentHashMap<>();
        return true;
    }

    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return false;
    }

    public static void activityChat(int activityId, WorldMessageProto.WorldMessageTempMsg chatMsg) {
        ActivityInfo activityInfo = ActivityInfoMgr.getActivityInfo(activityId);
        if (!ActivityHelper.activityInShowTime(activityInfo)) {
            return;
        }

        chatMsg = appendAreaParam(activityInfo, chatMsg);//附加一下分组参数

        if ((activityInfo.getType() == eActivityType.CrossRankActivity.getValue() &&
                activityInfo.getChildType() == eCrossRankActivityType.CrossBanquetPopularityRiseRank.getValue())) {
            if (activityInfo.getServerIdList2().size() > 0) {
                //赴宴扩大范围，因为不同活动，所以增加了返回活动的类型和子类型，让客户端可以区分开来；
                WorldMessageProto.WorldMessageTempMsg.Builder builder = chatMsg.toBuilder();
                builder.setExtraParams(String.format("%d_%d", activityInfo.getType(), activityInfo.getChildType()));
                WorldMessageProto.WorldMessageTempMsg worldMessageTempMsg = builder.build();
                activityExtensionChat(activityInfo, worldMessageTempMsg);
                return;
            }
        }
        if(activityInfo.getType() == eActivityType.PeakSeacraftActivity.getValue() && !StringUtils.isNullOrEmpty(chatMsg.getExtraParams())){
            PeakSeacraftMgr.addAreaGroupChatMsg(activityId, chatMsg.getGroupId(), chatMsg);
            return;
        }


        if (!chatMsgMap.containsKey(activityId)) {
            synchronized (chatMsgMap) {
                if (!chatMsgMap.containsKey(activityId)) {
                    chatMsgMap.put(activityId, new ConcurrentHashMap<>());
                }
            }
        }
        Map<Integer, WorldMessageProto.WorldMessageListMsg.Builder> groupMap = chatMsgMap.get(activityId);
        int groupId = chatMsg.getGroupId();

        // 如果是地区报名活动
        if (CrossChannelHelper.isCross3(CrossBattleServer.getInstance().getServerId())) {
            if(chatMsg.getType() == eMessageType.EnterNameActivityChat.getValue() || chatMsg.getType() == eMessageType.EnterNameActivityGroupChat.getValue()){
                groupId = 0;
                //设置报名的地区
                if(Cross3EnterNameMgr.getMatchMap().containsKey(activityId)){
                    int areaId = Cross3EnterNameMgr.getUserEnterNameGroupId(activityId, chatMsg.getUserId());
                    chatMsg = chatMsg.toBuilder().setGroupId(areaId).build();
                    //设置匹配分组频道
                    if(chatMsg.getType() == eMessageType.EnterNameActivityGroupChat.getValue()){
                        groupId = Cross3EnterNameMgr.getMatchGroupId(activityId, chatMsg.getUserId());
                    }
                }
            }
        }

        if (!groupMap.containsKey(groupId)) {
            synchronized (chatMsgMap) {
                if (!groupMap.containsKey(groupId)) {
                    groupMap.put(groupId, WorldMessageProto.WorldMessageListMsg.newBuilder());
                }
            }
        }
        WorldMessageProto.WorldMessageListMsg.Builder chatListMsg = groupMap.get(groupId);
        synchronized (chatListMsg) {
            if (chatListMsg.getDataListCount() >= MAX_MESSAGE_COUNT) {
                chatListMsg.removeDataList(0);
            }
            chatListMsg.addDataList(chatMsg);
        }

        // 转发聊天到游戏服
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.S_WORLD_MESSAGE_TRANSFER, chatMsg);
        if (activityInfo.getType() == eActivityType.WasheActivity.getValue() || activityInfo.getType() == eActivityType.CrossPasture.getValue()
                || activityInfo.getType() == eActivityType.AreaWashePkActivity.getValue()) {
            // 全部区服
            MessageHelper.sendAllServer(pbMsg);
        } else {
            // 活动范围内本渠道区服
            int channelId = ConfigHelper.getInt("channelId");
            for (long serverId : activityInfo.getServerIdList()) {
                if (channelId == ServerListMgr.getChannelId(serverId)) {
                    MessageHelper.sendPacket(serverId, 0, pbMsg);
                }
            }
        }
    }

    //这里存储额外的聊天记录，比如，赴宴争霸，和小当家第二阶段
    public static void activityExtensionChat(ActivityInfo activityInfo, WorldMessageProto.WorldMessageTempMsg chatMsg) {
        if (!chatExtensionMsgMap.containsKey(activityInfo.getServerListStr2())) {
            synchronized (chatExtensionMsgMap) {
                if (!chatExtensionMsgMap.containsKey(activityInfo.getServerListStr2())) {
                    chatExtensionMsgMap.put(activityInfo.getServerListStr2(), WorldMessageProto.WorldMessageListMsg.newBuilder());
                }
            }
        }
        WorldMessageProto.WorldMessageListMsg.Builder chatListMsg = chatExtensionMsgMap.get(activityInfo.getServerListStr2());
        synchronized (chatExtensionMsgMap) {
            if (chatListMsg.getDataListCount() >= MAX_MESSAGE_COUNT) {
                chatListMsg.removeDataList(0);
            }
            chatListMsg.addDataList(chatMsg);
        }
        YanQuMessage pbMsg = YanQuMessageUtils.buildMessage(Protocol.A_WORLD_MESSAGE_TRANSFER, chatMsg);
        int channelId = ConfigHelper.getInt("channelId");

        for (long serverId : activityInfo.getServerIdList2()) {
            if (channelId == ServerListMgr.getChannelId(serverId)) { // 只转发给相同渠道
                MessageHelper.sendPacket(serverId, 0, pbMsg);
            }
        }
    }

    public static WorldMessageProto.WorldMessageListMsg.Builder getChatListMsg(int activityId, int param2,int groupId) {
        ActivityInfo activityInfo = ActivityInfoMgr.getActivityInfo(activityId);
        if (activityInfo.getType() == eActivityType.CrossRankActivity.getValue()) {
            if (activityInfo.getChildType() == eCrossRankActivityType.CrossBanquetPopularityRiseRank.getValue()) {
                if (activityInfo.getServerIdList2().size() > 0) {
                    return chatExtensionMsgMap.get(activityInfo.getServerListStr2());
                }
            }
        }

        if (param2 > 0 && activityInfo.getType() == eActivityType.PeakSeacraftActivity.getValue()) {//巅峰海战战场聊天专用
            return PeakSeacraftMgr.getAreaGroupChatListMsg(activityId, groupId, param2);
        }
        Map<Integer, WorldMessageProto.WorldMessageListMsg.Builder> groupMap = chatMsgMap.get(activityId);

        if (groupMap != null) {
            return groupMap.get(groupId);
        }
        return null;
    }

    /**
     * 清空聊天记录
     */
    public static void clearChatMsg(int activityId) {
        // 清空服务器的记录
        chatMsgMap.remove(activityId);
        // 同步给客户端清空
        ActivityInfo activityInfo = ActivityInfoMgr.getActivityInfo(activityId);
        if (activityInfo != null) {
            // 有活动就发给活动对应区服
            for (long serverId : activityInfo.getServerIdList()) {
                WorldMessageProto.SyncClearChatMsg.Builder builder = WorldMessageProto.SyncClearChatMsg.newBuilder();
                builder.setActivityId(activityId);
                YanQuMessage message = YanQuMessageUtils.buildMessage(AgentProtocol.A_SYNC_CLEAR_CHAT, builder);
                MessageHelper.sendPacket(serverId, 0, message);
            }
            if(activityInfo.getType() == eActivityType.ChannelTonBingActivity.getValue()){
                WorldMessageProto.SyncClearChatMsg.Builder builder = WorldMessageProto.SyncClearChatMsg.newBuilder();
                builder.setActivityId(activityId);
                getLogger().error("跨服发送清空跨域统兵{}的聊天",activityId);
                MessageHelper.sendChannelServer(YanQuMessageUtils.buildMessage(ChannelProtocol.N_CHANNEL_CLEAR_CHAT, builder));
            }
        } else {
            // 没活动就全部发，反正ID唯一
            WorldMessageProto.SyncClearChatMsg.Builder builder = WorldMessageProto.SyncClearChatMsg.newBuilder();
            builder.setActivityId(activityId);
            YanQuMessage message = YanQuMessageUtils.buildMessage(AgentProtocol.A_SYNC_CLEAR_CHAT, builder);
            MessageHelper.sendAllServer(message);
        }
    }

    public static WorldMessageProto.WorldMessageTempMsg appendAreaParam(ActivityInfo activityInfo, WorldMessageProto.WorldMessageTempMsg chatMsg) {
        WorldMessageProto.WorldMessageTempMsg.Builder builder = chatMsg.toBuilder();
        String areaParam = null;
        if (activityInfo.getType() == eActivityType.PeakSeacraftActivity.getValue()) {
            int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityInfo, chatMsg.getUserId());
            PeakSeacraftActivity activity = PeakSeacraftMgr.getPeakSeacraftActivity(activityInfo.getActivityId(), groupId);
            if (activity != null) {
                areaParam = activity.getUserAreaParam(chatMsg.getUserId());
            }
        } else if (activityInfo.getType() == eActivityType.PeakStrongHold.getValue()) {
            int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityInfo, chatMsg.getUserId());
            PeakStrongholdActivityModel activityModel = CrossPeakStrongholdMgr.getActivityModel(activityInfo.getActivityId(), groupId);
            if (activityModel != null) {
                areaParam = activityModel.getUserAreaParam(chatMsg.getUserId());
            }
        } else if (activityInfo.getType() == eActivityType.SuiTang.getValue()) {
            int groupId = Cross2UnionActivityGroupMgr.getGroupId(activityInfo, chatMsg.getUserId());
            CrossSuiTangActivity activity = CrossSuiTangMgr.getActivity(activityInfo.getActivityId(), groupId);
            if (activity != null) {
                areaParam = activity.getUserAreaParam(chatMsg.getUserId());
            }
        } else if (activityInfo.getType() == eActivityType.TonBingActivity.getValue()) {
            CrossTonBingActivity activity = CrossTonBingMgr.getActivity(activityInfo.getActivityId());
            if (activity != null) {
                areaParam = activity.getUserAreaParam(chatMsg.getUserId());
            }
        } else if (activityInfo.getType() == eActivityType.JiuZhou.getValue()) {
            CrossJiuZhouActivity activity = CrossJiuZhouMgr.getActivity(activityInfo.getActivityId());
            if (activity != null) {
                areaParam = activity.getUserAreaParam(chatMsg.getUserId());
            }
        } else if (activityInfo.getType() == eActivityType.RankUnionWar.getValue()) {
            CrossRankUnionWarActivity activity = CrossRankUnionWarMgr.getActivity(activityInfo.getActivityId());
            if (activity != null) {
                areaParam = activity.getUserAreaParam(chatMsg.getUserId());
            }
        } else {
            return chatMsg;
        }

        if (areaParam != null) {
            builder.setAreaParam(areaParam);
        }

        return builder.build();
    }
}
